import { createI18n } from 'vue-i18n';

//从浏览器cookie中读取用户选中的语言
import { getLanguage } from '@/utils/cookies';

// element-plus 的组件的语言
import elementEnLocale from 'element-plus/lib/locale/lang/en';
import elementZhLocale from 'element-plus/lib/locale/lang/zh-cn';

// User defined lang  用户自定义网站的语言
import enLocale from './lang/en';
import zhLocale from './lang/zh-cn';

// 定义语言
const messages = {
  en: {
    ...enLocale,
    ...elementEnLocale,
  },
  'zh-cn': {
    ...zhLocale,
    ...elementZhLocale,
  },
};

export const getLocale = () => {
  //从浏览器cookies中读取i18nLang
  const cookieLanguage = getLanguage();
  //如果有值返回语言
  if (cookieLanguage) {
    return cookieLanguage;
  }
  // 得到浏览器的自带语言  navigator.language --> 'zh-CN'
  const language = navigator.language.toLowerCase();
  //得到messages对象中的键  ['en','zh-cn']
  const locales = Object.keys(messages);
  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      return locale;
    }
  }

  return 'zh';
};

const i18n = createI18n({
  locale: getLocale(),
  messages: messages,
});

export default i18n;
